package com.etc.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

//@RestController
@Controller
public class UploadImgController {

    /**
     * 非Ajax. 文件上传测试
     * @param myfile
     * @param request
     * @return
     */
    @PostMapping("uploadImg1/")
    public String uploadImage1(MultipartFile myfile[], HttpServletRequest request){
        //输出myfile
        System.out.println("uploadImage1 myfile: "+myfile);
        //数组元素有几个? 遍历数组
        for (MultipartFile multipartFile : myfile) {
            System.out.println("multipartFile.getOriginalFilename() :"+multipartFile.getOriginalFilename());
            //如果是当前项目部署路径(是部署路径) =>物理位置+当前文件真实名字
            File file = new File(request.getRealPath("/images/")+multipartFile.getOriginalFilename());
            //上传文件,参数是一个File对象，指定就是文件目标位置
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

    /**
     * 处理ajax请求的一个方法
     * @param myfile
     * @param request
     * @return
     */
    @PostMapping("uploadImg2/")
    @ResponseBody
    public String uploadImage2(MultipartFile myfile[], HttpServletRequest request){
        //输出myfile
        System.out.println("uploadImage2 myfile: "+myfile);
        //数组元素有几个? 遍历数组
        for (MultipartFile multipartFile : myfile) {
            System.out.println("multipartFile.getOriginalFilename() :"+multipartFile.getOriginalFilename());
            //如果是当前项目部署路径(是部署路径) =>物理位置+当前文件真实名字
            File file = new File(request.getRealPath("/images/")+multipartFile.getOriginalFilename());
            //上传文件,参数是一个File对象，指定就是文件目标位置
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
}
